<template>
  <div>
    <div class="t_h2">板房待打板明细及超时详情</div>
    <!-- 查询表单和按钮 -->
    <div class="search-form">
      <div class="search-form-put">
        <div class="search-form-button">
          <vxe-button @click="handleSearch">查询</vxe-button>
          <vxe-button @click="clears">清空查询条件</vxe-button>
          <vxe-button @click="toggleFormRow">
            {{ showFormRow ? '隐藏查询条件' : '显示查询条件' }}
          </vxe-button>
          <vxe-button @click="exportData" v-show="showFormButton">导出</vxe-button>
          <vxe-button content="新增停产时间" @click="showStopProducDateAdd" v-show="showFormButton"></vxe-button>
          <vxe-button content="查询停产时间" @click="showStopProducDateSearch" v-show="showFormButton"></vxe-button>
          <vxe-button @click="toggleFormButton">
            {{ showFormButton ? '<<<' : '>>>' }}
          </vxe-button>
        </div>

        <div class="form-row" v-show="showFormRow">
          <div class="form-group">
            <label>打板单号:</label>
            <vxe-input type="text" v-model="orderNo" placeholder="打板单号"></vxe-input>
          </div>
          <div class="form-group">
            <label>客户:</label>
            <vxe-select v-model="clothLineName" placeholder="请选择客户选项">
              <vxe-option
                  v-for="type in clothLineNames"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value">
              </vxe-option>
            </vxe-select>
          </div>
          <div class="form-group">
            <label>打板类型:</label>
            <vxe-select v-model="pendType" placeholder="请选择打板类型选项">
              <vxe-option
                  v-for="type in pendTypes"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value">
              </vxe-option>
            </vxe-select>
          </div>
          <div class="form-group">
            <label>是否超时:</label>
            <vxe-select v-model="timeoutType" placeholder="请选择是否超时选项">
              <vxe-option
                  v-for="type in timeoutTypes"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value">
              </vxe-option>
            </vxe-select>
          </div>

          <div class="form-group">
            <label>成分分类:</label>
            <vxe-select v-model="componentType" placeholder="请选择成分分类选项">
              <vxe-option
                  v-for="type in componentTypes"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value">
              </vxe-option>
            </vxe-select>
          </div>
          <div class="form-group">
            <label>产编:</label>
            <vxe-input type="text" v-model="productCode" placeholder="产编"></vxe-input>
          </div>
          <div class="form-group">
            <label>布种:</label>
            <vxe-input type="text" v-model="productName" placeholder="布种"></vxe-input>
          </div>
          <div class="form-group">
            <label>颜色:</label>
            <vxe-input type="text" v-model="colorName" placeholder="颜色"></vxe-input>
          </div>
        </div>
      </div>
    </div>

    <!--    resizable:允许列宽通过拖动调整。
        border:为表格添加边框。
        show-overflow:当内容超出单元格宽度时，显示省略号（...）。
        show-header-overflow:当表头内容超出宽度时，显示省略号（...）。
        show-header-overflow="title" 表示只在表头内容超出时显示省略号。
        show-footer-overflow:当表尾内容超出宽度时，显示省略号（...）。
        ref="xTable":为表格组件设置一个引用名 xTable，可以通过 this.$refs.xTable 在 JavaScript 中访问表格实例。
        class="mytable-scrollbar":为表格添加自定义 CSS 类名 mytable-scrollbar，用于自定义样式。
        v-loading="loading":根据 loading 变量的值显示或隐藏加载状态（通常是一个加载动画）。
        :height="tableHeight":设置表格的固定高度（tableHeight 是一个变量，需要在 data 中定义）。
        :sort-config="{trigger: 'cell'}":配置排序功能，trigger: 'cell' 表示点击单元格时触发排序。
        :expand-config="{accordion: true, lazy: true, loadMethod: loadContentMethod}":配置展开行功能：
        accordion: true：以手风琴模式展开（一次只能展开一行）。
        lazy: true：懒加载展开行内容。
        loadMethod: loadContentMethod：指定加载展开行内容的方法（loadContentMethod 是一个方法，需要在 methods 中定义）。
        :scroll-x="{enabled: true, gt: 10}":配置水平滚动：
        enabled: true：启用水平滚动。
        gt: 10：当列数超过 10 时显示水平滚动条。
        :scroll-y="{enabled: true, gt: 100}":配置垂直滚动：
        enabled: true：启用垂直滚动。
        , loadMethod: loadContentMethod
        gt: 100：当行数超过 100 时显示垂直滚动条。-->
    <!--显示待打板数据-->
    <vxe-table
        resizable
        border
        show-overflow
        show-header-overflow
        show-footer-overflow
        ref="xTable"
        class="mytable-scrollbar"
        :cell-style="cellStyle"
        v-loading="loading"
        :height="tableHeight"
        :sort-config="{trigger: 'cell'}"
        :expand-config="{accordion: true, lazy: true}"
        :scroll-x="{enabled: true, gt: 10}"
        :scroll-y="{enabled: true, gt: 100}"
        :data="tableData">
      <vxe-column type="seq" title="序号" show-header-overflow="title" align="center" header-align="center" :width="60"/>
      <vxe-column field="cloth_line_name" title="客户" align="center" sortable
                  show-header-overflow="title" :width="100" header-align="center"/>
      <vxe-column field="order_no" title="打板单号" align="left" sortable
                  show-header-overflow="title" class-name="hide-sort-icon" header-align="center"/>
      <vxe-column field="sample_doc_no" title="打样单号" align="center" sortable
                  show-header-overflow="title" header-align="center" />
      <vxe-column field="type" title="打板类型" align="center" sortable
                  show-header-overflow="title" header-align="center"/>
      <vxe-column field="finish_time" title="交期" align="center" :width="120" sortable
                  show-header-overflow="title" :formatter="formatDate" header-align="center"/>
      <vxe-column field="examination_date" title="化验室接收时间" align="center" sortable
                  show-header-overflow="title" :formatter="formatDateTime" header-align="center" />
      <vxe-column field="timeout_standard" title="超时标准" align="center" sortable
                  show-header-overflow="title" :width="100" header-align="center" />
      <vxe-column field="examination_times" title="审核时长" align="center" sortable
                  show-header-overflow="title" :width="100" header-align="center" />
      <vxe-column field="stopproduct_times" title="停产时长" align="center" sortable
                  show-header-overflow="title" :width="100" header-align="center" />
      <vxe-column field="is_timeout" title="超时" align="center" sortable
                  show-header-overflow="title" :width="80" header-align="center" />
      <vxe-column field="dyeing_type" title="成分分类" align="center" sortable
                  show-header-overflow="title" :width="100" header-align="center" />
      <vxe-column field="dyelot_code" title="缸号" align="center" sortable
                  show-header-overflow="title" header-align="center"/>
      <vxe-column field="product_code" title="产编" align="center" sortable
                  show-header-overflow="title" :width="100" header-align="center"/>
      <vxe-column field="product_name" title="布种" align="center" sortable
                  show-header-overflow="title" header-align="center"/>
      <vxe-column field="color_name" title="颜色" align="center" sortable
                  show-header-overflow="title" header-align="center"/>
      <!--      <vxe-column field="salesman" title="销售名字" align="center" sortable show-header-overflow="title" />-->
      <!--      <vxe-column field="dyeing_color_code" title="色号" align="center" sortable show-header-overflow="title" />-->
      <!--      <vxe-column field="order_state" title="是否接收" align="center" sortable show-header-overflow="title" />-->
      <!--      <vxe-column field="cloth_line_customer" title="布行客户" align="center" sortable show-header-overflow="title" />-->
      <!--      <vxe-column field="dyeing_type_name" title="染色分类" align="center" sortable show-header-overflow="title" />-->
    </vxe-table>

    <!--显示新增弹出框-->
    <vxe-modal
        v-model="addDialogVisible"
        title="新增停产时间"
        width="650"
        min-width="400"
        min-height="300"
        resize
        destroy-on-close
        style="font-weight: bold;letter-spacing: 3px;font-size: 16px; "
    >
      <template #default>
        <!-- 这里放新增表单内容 -->
        <div class="form-container">
          <el-form :model="addFormData">
            <el-form-item label="开始时间" required>
              <el-date-picker v-model="addFormData.startDate"
                  type="datetime" placeholder="选择开始时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"/>
            </el-form-item>
            <el-form-item label="结束时间" required>
              <el-date-picker v-model="addFormData.endDate"
                  type="datetime" placeholder="选择结束时间"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"/>
            </el-form-item>
            <el-form-item label="原因" >
              <el-input type="textarea" :rows="10"
                   v-model="addFormData.reason" style = "width: 90%"
              />
            </el-form-item>
          </el-form>

        </div>
        <div class="addfooter">
          <vxe-button @click="addDialogVisible = false">取消</vxe-button>
          <vxe-button type="submit" status="primary" @click="handleAddSubmit">确认</vxe-button>
        </div>
      </template>
    </vxe-modal>

    <!--显示查询弹出框-->
    <vxe-modal
        v-model="searchDialogVisible"
        title="查询停产时间"
        width="900"
        min-width="600"
        min-height="400"
        resize
        style="font-weight: bold;letter-spacing: 3px;font-size: 16px; "
        @close = "handleModalClose"
    >
      <template #default>
        <!-- 这里放查询条件和结果表格 -->
        <div class="search-container">
          <!--查询条件-->
          <div class="search-form-container">
            <div class="form-row-f">
              <label>从:</label>
              <calendar v-model="searchStartDate" show-date-only :disabled-days-of-week="disabled" :format="format"
                        :clear-button="clear" :lang="lang" :position="position"
                        :pane="1" :range-bus="getBus" :range-status="1"></calendar>
              <label>至:</label>
              <calendar v-model="searchEndDate" show-date-only :disabled-days-of-week="disabled" :format="format"
                        :clear-button="clear" :lang="lang" :position="position"
                        :pane="1" :range-bus="getBus" :range-status="2"></calendar>
            </div>
            <div class="searchtop">
              <vxe-button @click="handleSearchD">查询</vxe-button>
              <vxe-button @click="deleteD">删除</vxe-button>
              <vxe-button @click="closeStp">关闭</vxe-button>
            </div>
          </div>
          <!--数据主体-->
          <vxe-table
              border
              height="300"
              :data="tableDataD"
              ref="tableRef"
              @checkbox-change="handleCheckboxChange"
              @checkbox-all="selectAllCheckboxChange"
          >
            <vxe-column type="checkbox" width="50" align="center"></vxe-column>
            <vxe-column field="id" title="唯一ID" width="80" :visible="false"></vxe-column>
            <vxe-column type="seq" title="序号" width="60" align="center"/>
            <vxe-column field="startDate" title="开始时间" :formatter="formatDateTime"/>
            <vxe-column field="endDate" title="结束时间" :formatter="formatDateTime"/>
            <vxe-column field="timeLength" title="时长" width="80" align="right"/>
            <vxe-column field="reason" title="原因"></vxe-column>
          </vxe-table>
        </div>
      </template>
    </vxe-modal>

  </div>

</template>

<script>
import * as XLSX from "xlsx";
import { saveAs } from 'file-saver';
import {getPatternMaking, addStopProduct,deleteStopProduct, searchStopProduct} from '@/services/DataService';
import Vue, {ref} from "vue";
import Calendar from 'vue2-slot-calendar';
import 'vxe-table/lib/style.css';

export default {
  name: "ShowDateBF",
  components: {
    calendar: Calendar,
  },
  watch:{
    clothLineName(clothLineName){
      this.clothLineName = clothLineName.trim();
    },
    pendType(pendType){
      this.pendType = pendType.trim();
    },
    timeoutType(timeoutType){
      this.timeoutType = timeoutType.trim();
    },
    componentType(componentType){
      this.componentType = componentType.trim();
    },
    orderNo(orderNo){
      this.orderNo = orderNo.trim();
    },
    productCode(productCode){
      this.productCode = productCode.trim();
    },
    productName(productName){
      this.productName = productName.trim();
    },
    colorName(colorName){
      this.colorName = colorName.trim();
    }
  },
  data () {
    return {
      showFormButton: false, // 控制按钮的显示和隐藏
      showFormRow: false, // 控制查询条件的显示和隐藏
      loading: true,//加载状态
      tableHeight: 0, // 响应式属性，用于存储表格高度
      tableData: [], // 初始化为空数组--待打板数据
      //查询条件初始化
      orderNo: "",
      productCode: "",
      productName: "",
      colorName: "",
      clothLineName: "",
      pendType: "",
      timeoutType: "",
      componentType: "",
      //下拉框初始化
      clothLineNames: [
        { value: '*', label: '' },
        { value: '怡丰', label: '怡丰' },
        { value: '力汇', label: '力汇' },
        { value: '千城', label: '千城' },
        { value: '粤隆', label: '粤隆' },
      ],
      pendTypes: [
        { value: '*', label: '' },
        { value: '头缸复办', label: '头缸复办' },
        { value: '新纱牌复办', label: '新纱牌复办' },
        { value: '打板', label: '打板' },
        { value: '染部复办', label: '染部复办' },
      ],
      timeoutTypes: [
        { value: '*', label: '' },
        { value: '1', label: '超时' },
        { value: '0', label: '未超时' },
      ],
      componentTypes: [
        { value: '*', label: '' },
        { value: 'CVC', label: 'CVC' },
        { value: 'TC', label: 'TC' },
        { value: 'TR', label: 'TR' },
        { value: 'T', label: 'T' },
        { value: '棉', label: '棉' },
        { value: 'R', label: 'R' },
        { value: '有机棉', label: '有机棉' },
        { value: '醋酸', label: '醋酸' },
        { value: '其他', label: '其他' },
      ],
      // 弹出框初始化数据
      addDialogVisible: false,
      searchDialogVisible: false,
      addFormData: {
        startDate: (new Date()).toLocaleString('sv-SE', {
                      timeZone: 'UTC',
                      year: 'numeric',
                      month: '2-digit',
                      day: '2-digit',
                      hour: '2-digit',
                      minute: '2-digit',
                      second: '2-digit',
                      hour12: false
                    }).replace(' ', 'T').replace('T', ' '),
        endDate: (new Date()).toLocaleString('sv-SE', {
                    timeZone: 'UTC',
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                  }).replace(' ', 'T').replace('T', ' '),
        reason: ''
      },
      tableDataD: [],
      searchStartDate: ref(new Date()),
      searchEndDate: ref(new Date()),
      format: 'yyyy-MM-dd',
      disabled: [],
      startDate: ref(new Date()),
      endDate: ref(new Date()),
      clear: false,
      placeholder: "Start Date",
      position: "left",
      lang: "",
      bus: new Vue(),
      selectedRows: [], // 存储选中的行
      deleteIsOk: false
    }
  },
  async mounted () {
    document.title = '板房超时监控数据看板';
    this.setWindowHeight(); // 设置初始高度
    window.addEventListener('resize', this.setWindowHeight); // 监听窗口大小变化
    // 调用一个异步函数来获取数据大小
    this.fetchDataAndLoadTable();
  },
  methods: {
    // 清空查询条件
    clears() {
      // 清空查询条件
      this.orderNo = '';
      this.clothLineName = '';
      this.pendType = '';
      this.timeoutType = '';
      this.componentType = '';
      this.productCode = '';
      this.productName = '';
      this.colorName = '';

      // 重新查询数据
      this.handleSearch();
    },
    // 显示和隐藏查询按钮,
    toggleFormButton() {
      this.showFormButton = !this.showFormButton; // 切换按钮的显示状态
    },
    // 显示和隐藏查询条件,
    toggleFormRow() {
      this.showFormRow = !this.showFormRow; // 切换查询条件的显示状态
      this.setWindowHeight()
    },
    // 渲染颜色
    cellStyle({columnIndex}){
      if(columnIndex==5){
        return {'background-color': '#E2EFD9'}
      }else if (columnIndex==6){
        return {'background-color': '#E2EFF9'}
      }
      else if (columnIndex==10){
        return {
          'color': 'red',
          'font-weight': 'bold'
        }
      }
    },

    // 修改日期格式
    formatDate({ cellValue }) {
      if (!cellValue) return '';
      const date = new Date(cellValue);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    formatDateTime({ cellValue }) {
      if (!cellValue) return '';
      const date = new Date(cellValue);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },

    // 设定宽度和高度
    setWindowHeight() {
      const wheightpx = this.showFormRow?240:155
      // 计算可用高度，这里只是一个示例，你可能需要根据你的布局进行调整
      const windowHeight = window.innerHeight;
      // 假设你要留给表格之外的内容（如页眉、页脚等）100px的高度
      this.tableHeight = windowHeight - wheightpx;
    },

    // 查询
    async handleSearch() {
      this.loading = true; // 开始加载前设置loading为true
      try {
        await this.expandRows();
      } catch (error) {
        console.error('获取tableData失败:', error);
      } finally {
        this.loading = false; // 无论expandRows是否成功，都设置loading为false
      }
    },
    async expandRows() {
      this.getDates()
      const res = await getPatternMaking(this.searchStartDate,this.searchEndDate,this.orderNo,this.clothLineName,this.pendType,this.timeoutType,this.componentType,this.productCode,this.productName,this.colorName);
      if (res!=undefined){
        // 所有数据加载完成后，更新tableData
        this.tableData = res.map(item => ({
          order_no: item.打板单号,
          sample_doc_no: item.打样单号,
          dyelot_code: item.缸号,
          finish_time: item.交期,
          type: item.打板类型,
          cloth_line_name: item.客户,
          product_code: item.产编,
          product_name: item.布种,
          color_name: item.颜色,
          examination_date: item.化验室接收时间,
          examination_times: item.审核时长,
          stopproduct_times: item.停产时长,
          dyeing_type: item.成分分类,
          timeout_standard: item.超时标准,
          is_timeout: item.是否超时,
        }));
      }else{
        this.tableData = [];
      }
    },

    // 异步获取数据
    async fetchDataAndLoadTable() {
      try {
        this.getDates()
        const res = await getPatternMaking(this.searchStartDate,this.searchEndDate,this.orderNo,this.clothLineName,this.pendType,this.timeoutType,this.componentType,this.productCode,this.productName,this.colorName);
        // 等待 DOM 更新后再加载数据
        this.$nextTick(() => {
          const $table = this.$refs.xTable;

          this.mockList(res).then(data => {
            if ($table) {
              $table.loadData(data);
            }
          });
        });
        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.error('Error fetching data:', error);
        // 错误处理...
      }
    },
    // 刷新表格数据（更新停产信息-非数据库获取）
    async refreshTable() {
      //查询停产信息明细
      this.getDates()
      const responseData_sp = await searchStopProduct(this.searchStartDate,this.searchEndDate)

      // 获取表格数据
      const data = this.$refs.xTable.getTableData().tableData;
      // 遍历数据并根据 columnA 的值更新 columnB
      data.forEach(row => {
        let examination_date = row.examination_date//化验室接收时间
        let timeout_standard = row.timeout_standard//超时标准
        let examination_times = row.examination_times//审核时长
        let sum_timeLength = 0
        if (Array.isArray(responseData_sp)) {
            responseData_sp.forEach((re) => {
                const startDatesp = re.t_start_date; //停产开始时间
                const timeLength = re.t_timeLength; //停产时长
                console.log(startDatesp,timeLength)
                if (examination_date < startDatesp){
                  sum_timeLength += timeLength
                }
            });
        }
        if (sum_timeLength>0){
            row.stopproduct_times = sum_timeLength
            examination_times = examination_times-sum_timeLength
            //判断 是否超时
            if(timeout_standard<=examination_times){
              row.is_timeout = '超时'
            }else{
              row.is_timeout = ''
            }
        }else{
          row.stopproduct_times = null
          row.is_timeout = ''
        }
      });

      // 重新设置表格数据以触发更新
      this.tableData = [...data];
    },
    mockList (res) {
      const size = res.length;
      return new Promise(resolve => {
        const list = []
        for (let index = 0; index < size; index++) {
          list.push({
            order_no: res[index].打板单号,
            sample_doc_no: res[index].打样单号,
            dyelot_code: res[index].缸号,
            finish_time: res[index].交期,
            type: res[index].打板类型,
            cloth_line_name: res[index].客户,
            product_code: res[index].产编,
            product_name: res[index].布种,
            color_name: res[index].颜色,
            examination_date: res[index].化验室接收时间,
            examination_times: res[index].审核时长,
            stopproduct_times: res[index].停产时长,
            dyeing_type: res[index].成分分类,
            timeout_standard: res[index].超时标准,
            is_timeout: res[index].是否超时
            // salesman: res[index].销售,
            // order_state: res[index].是否接收,
            // cloth_line_customer: res[index].布行客户,
            // dyeing_color_code: res[index].色号,
            // dyeing_type_name: res[index].染色分类,
          })
        }
        resolve(list)
      })
    },

    // 导出
    async exportData() {
      try {
        this.loading = true;
        // 发送请求并获取数据
        this.getDates()
        const dataH = await getPatternMaking(this.searchStartDate,this.searchEndDate,this.orderNo,this.clothLineName,this.pendType,this.timeoutType,this.componentType,this.productCode,this.productName,this.colorName);
        // 转换你的数据以匹配标题
        const dataSheet1 = dataH.map((item, index) => ({
          序号: index+1,
          打板单号: item.打板单号,
          打样单号: item.打样单号,
          缸号: item.缸号,
          成分分类: item.成分分类,
          交期: item.交期,
          化验室接收时间: item.化验室接收时间,
          审核时长: item.审核时长,
          超时标准: item.超时标准,
          是否超时: item.是否超时,
          打板类型: item.打板类型,
          客户: item.客户,
          产编: item.产编,
          布种: item.布种,
          色号: item.色号,
          颜色: item.颜色,
          销售人名字: item.销售,
          是否接收: item.是否接收,
        }));

        const workbook = XLSX.utils.book_new();
        const worksheet1 = XLSX.utils.json_to_sheet(dataSheet1);

        //列宽
        const columnWidthsH = [5, 15, 30, 15, 10, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15];
        worksheet1['!cols'] = columnWidthsH.map(width => ({ wch: width }));

        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(workbook, worksheet1, '数据明细');
        // 生成 Excel 文件的 Blob 对象
        const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
        //触发下载
        const blob = new Blob([wbout], { type: 'application/octet-stream' });
        saveAs(blob, '待打板明细及超时数据明细_'+Date.now()+'.xlsx');
        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.error('Error exporting data:', error);
      }
    },

    //弹出框相关函数
    showStopProducDateAdd() {
      this.addDialogVisible = true
      // 重置表单
      this.addFormData = {

        startDate: (new Date()).toLocaleString('sv-SE', {
                      timeZone: 'UTC',
                      year: 'numeric',
                      month: '2-digit',
                      day: '2-digit',
                      hour: '2-digit',
                      minute: '2-digit',
                      second: '2-digit',
                      hour12: false
                    }).replace(' ', 'T').replace('T', ' '),
        endDate: (new Date()).toLocaleString('sv-SE', {
                  timeZone: 'UTC',
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit',
                  hour12: false
                }).replace(' ', 'T').replace('T', ' '),
        reason: ''
      }
    },
    showStopProducDateSearch() {
      this.searchDialogVisible = true
      this.getDates()
      this.handleSearchD()
    },
    // 获取当月月初第一天，和下月月初第一天
    getDates(){
      // 获取当前日期
      let currentDate = new Date();

      // 获取当前月份的第一天
      const firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 2);

      // 获取下个月的第一天
      const firstDayOfNextMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 2);

      this.searchStartDate = firstDayOfMonth.toISOString().split('T')[0];
      this.searchEndDate = firstDayOfNextMonth.toISOString().split('T')[0];
    },

    // 新增停产时间信息
    handleAddSubmit() {
      // 这里处理新增提交逻辑
      if(this.addFormData.startDate == ''){
        this.$message.success("开始时间不能为空！")
      }else if(this.addFormData.endDate == ''){
        this.$message.success("结束时间不能为空！")
      }else if(this.addFormData.endDate < this.addFormData.startDate){
        this.$message.success("请选择正确的时间段！")
      }else{
        addStopProduct(this.addFormData)
        // 模拟提交成功
        this.$message.success('新增成功')
        this.addDialogVisible = false
        // 刷新表单信息
        // this.handleSearch();
        this.refreshTable();
      }
    },

    // 查询停产时间信息
    async handleSearchD() {
      // 查询逻辑
      const stopProductRes = await searchStopProduct(this.searchStartDate,this.searchEndDate)
      if (stopProductRes!=undefined){
        // 所有数据加载完成后，更新tableData
        this.tableDataD = stopProductRes.map((item, index) => ({
          序号: index+1,
          id: item.t_id,
          startDate: item.t_start_date,
          endDate: item.t_end_date,
          reason: item.t_reason,
          timeLength: item.t_timeLength,
        }));
      }else{
        this.tableData = [];
      }
    },
    handleCheckboxChange({ checked, row }) {
      if (checked) {
        // 如果选中，将行添加到 selectedRows
        this.selectedRows.push(row);
      } else {
        // 如果取消选中，从 selectedRows 中移除行
        this.selectedRows = this.selectedRows.filter(item => item !== row);
      }
    },
    selectAllCheckboxChange({ checked }) {
      this.$message.success(checked ? "全选" : "取消全选")
      const tableRef = this.$refs.tableRef
      if (checked) {
        // 全选：设置所有行为选中状态
        tableRef.setCheckboxRow(this.tableDataD, true)
        // 获取所有选中的行数据
        const allSelectedRows = tableRef.getCheckboxRecords()
        // 可以在这里更新你的选中数据状态
        this.selectedRows = allSelectedRows
      } else {
        // 取消全选：清除所有选中状态
        tableRef.clearCheckboxRow()
        // 获取取消全选后的选中数据（应该是空数组）
        const noSelectedRows = tableRef.getCheckboxRecords()
        // 更新选中数据状态
        this.selectedRows = noSelectedRows
      }
    },
    // 删除
    async deleteD() {
      if (this.selectedRows.length === 0) {
        this.$message.success("请选择要删除的行！")
        return;
      }
      // 确认删除
      if (confirm('确定要删除选中的行吗？')) {
        // 获取选中的行的 id 列表
        const idsToDelete = this.selectedRows.map(row => row.id);
        for (const id of idsToDelete) {
          await deleteStopProduct(id);
        }
        this.$message.success("删除成功！")

        // 过滤掉选中的行
        this.tableDataD = this.tableDataD.filter(row => !idsToDelete.includes(row.id));
        // 清空选中的行
        this.selectedRows = [];
        // 如果需要，可以重新加载表格数据
        this.handleSearchD()
        this.deleteIsOk = true
      }
    },

    //关闭窗口
    async closeStp(){
      this.searchDialogVisible = false
      console.log(this.deleteIsOk)
      // 重新查询数据
      if (this.deleteIsOk==true){
        // this.handleSearch();
        this.refreshTable()
        this.deleteIsOk = false
      }
    },
    //关闭窗口（X）
    async handleModalClose(){
      console.log(this.deleteIsOk)
      // 重新查询数据
      if (this.deleteIsOk==true){
        // this.handleSearch();
        this.refreshTable()
        this.deleteIsOk = false
      }
    },
    getBus() {
      return this.bus;
    },

  },


}
</script>

<style scoped>

.red-cell {
  background-color: red !important;
  color: white !important;
}

.t_h2 {
  /*color: rgb(0, 0, 0);*/
  display: block;
  font-size: 1.5em;
  margin-block-start: 0.83em;
  margin-block-end: 0.83em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
  unicode-bidi: isolate;
}

.search-form {
  /*padding: 15px;*/
  padding-bottom: 15px;
  padding-left: 15px;
  padding-right: 15px;
  background-color: #f5f5f5;
  border-radius: 5px;
}

.search-form-put {
  margin-bottom: 5px;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 5px;
}

.form-row2 {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-left: 5px;
}

.form-group {
  display: flex;
  align-items: center;
  min-width: 200px;
}

.form-group label {
  align-items: flex-end;
  width: 70px;
  margin-right: 5px;
  font-weight: bold;
}

.search-form-button {
  display: flex;
  justify-content: center; /* 水平居中对齐 */
  gap: 5px; /* 按钮之间的间距 */
  margin-bottom: 5px;
  align-items: center; /* 垂直居中对齐 */
  height: 40px; /* 设置容器高度，以便垂直居中 */
}

.search-form-button .vxe-button {
  font-weight: bold; /* 字体加粗 */
  letter-spacing: 3px; /* 增加字符间距 */
  font-size: 16px; /* 字体加大 */
  color: #2b2b2b;
  padding: 10px 10px; /* 增加按钮内边距，使其看起来更大 */
}


.form-container {
  padding-top: 10px;
  padding-left: 10px;
  padding-right: 10px;
}

.addfooter {
  display: flex;
  justify-content: flex-end; /* 将按钮放在右侧 */
  gap: 20px; /* 增加按钮之间的间距 */
  padding: 20px; /* 可根据需要调整 */
}
.search-container{
  padding-left: 10px;
  padding-right: 10px;
}
.search-form-container {
  padding-bottom: 10px;
  display: flex;
  align-items: center; /* 垂直居中 */
  gap: 20px; /* 调整表单和按钮之间的间距 */
  font-weight: bold; /* 字体加粗 */
}

.searchtop {
  display: flex;
  justify-content: flex-start; /* 将按钮放在右侧 */
  gap: 20px; /* 增加按钮之间的间距 */
}

.form-row-f {
  font-size: 15px; /* 字体加大 */
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  gap: 20px; /* 调整这个值以增加或减少间距 */
}

</style>
